package com.chat.common.user.service.adapter;

import cn.hutool.core.util.ObjectUtil;
import com.chat.common.common.domain.enums.YesOrNoEnum;
import com.chat.common.user.domain.entity.ItemConfig;
import com.chat.common.user.domain.entity.User;
import com.chat.common.user.domain.entity.UserBackpack;
import com.chat.common.user.domain.vo.req.BadgeResp;
import com.chat.common.user.domain.vo.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.beans.BeanUtils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class UserAdapter {
    public static User buildUserSave(String openId) {
        return User.builder().openId(openId).build();
    }


    public static User BuildAuthorize(Long id, WxOAuth2UserInfo userInfo) {
        User user = new User();
        user.setId(id);
        user.setAvatar(userInfo.getHeadImgUrl());
        user.setName(userInfo.getNickname());
        user.setSex(userInfo.getSex());
        return user;
    }

    public static UserInfoResp buildUserInfo(User user, Integer modifyNameCount) {
        UserInfoResp vo = new UserInfoResp();
        BeanUtils.copyProperties(user,vo);
        vo.setModifyNameChance(modifyNameCount);
        return vo;
    }

    /**
     *
     * @param itemConfigs  所有勋章
     * @param backpackList 用户拥有的勋章
     * @param user 用户
     * @return
     */
    public static List<BadgeResp> buildBadgeResp(List<ItemConfig> itemConfigs, List<UserBackpack> backpackList, User user) {
        if (ObjectUtil.isNull(user)) {
            // 这里 user 入参可能为空，防止 NPE 问题
            return Collections.emptyList();
        }
        Set<Long> collect = backpackList.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
       return itemConfigs.stream().map(i->{
            BadgeResp badgeResp = new BadgeResp();
            //将当前循环的徽章放入 返回体
            BeanUtils.copyProperties(i,badgeResp);
            //查询 该徽章 是否拥有
            badgeResp.setObtain(collect.contains(i.getId())?YesOrNoEnum.YES.getStatus():YesOrNoEnum.NO.getStatus());
            //是否佩戴 user表中itemId 和 itemConfig中的id
            badgeResp.setWearing(ObjectUtil.equal(i.getId(),user.getItemId())?YesOrNoEnum.YES.getStatus():YesOrNoEnum.NO.getStatus());
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing,Comparator.reverseOrder())//排序
                .thenComparing(BadgeResp::getObtain,Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
